<?php

namespace App\Services\Admin;

use App\Exceptions\LogicException;
use App\Models\Role;
use App\Models\RolePermission;

class RoleService
{
    protected $roleModel;
    protected $rolePermissionModel;

    public function __construct(Role $roleModel, RolePermission $rolePermissionModel)
    {
        $this->roleModel = $roleModel;
        $this->rolePermissionModel = $rolePermissionModel;
    }

    /**
     * 获取角色列表
     * @param array $params 查询参数
     * @return array
     */
    public function list(array $params): array
    {
        $fields = ['id', 'name', 'description', 'created_at', 'updated_at'];
        $result = $this->roleModel->list($params, $fields);
        foreach ($result['items'] as $key => &$value) {
            // 获取角色关联的权限
            $permissions = $this->rolePermissionModel->getRolePermissionsGroupName($value['id']);
            $value['permissions'] = $permissions;
        }
        return $result;
    }

    /**
     * 获取角色详情
     * @param int $id 角色ID
     * @return array
     * @throws LogicException
     */
    public function view(int $id): array
    {
        $fields = ['id', 'name', 'description'];
        $role = $this->roleModel->take(['id' => $id], $fields);
        if (empty($role)) {
            throw new LogicException('角色不存在');
        }

        // 查询角色关联的权限
        $permissions = $this->rolePermissionModel->search(['role_id' => $id], ['permission_id']);
        $role['permissions'] = array_column($permissions, 'permission_id');

        return $role;
    }

    /**
     * 创建角色
     * @param array $data 角色数据
     * @return array
     * @throws LogicException
     */
    public function create(array $data): array
    {
        // 检查角色名称是否已存在
        if ($this->roleModel->take(['full_name' => $data['name']], ['id'])) {
            throw new LogicException('角色名称已存在');
        }

        // 开启事务
        \DB::beginTransaction();
        try {
            // 创建角色
            $id = $this->roleModel->create($data);

            // 如果有权限数据，创建角色权限关联
            if (!empty($data['permissions']) && is_array($data['permissions'])) {
                foreach ($data['permissions'] as $permissionId) {
                    $this->rolePermissionModel->create([
                        'role_id' => $id,
                        'permission_id' => $permissionId
                    ]);
                }
            }

            \DB::commit();
            return ['id' => $id];
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new LogicException($e->getMessage());
        }
    }

    /**
     * 更新角色
     * @param int $id 角色ID
     * @param array $data 更新数据
     * @return array
     * @throws LogicException
     */
    public function update(int $id, array $data): array
    {
        if (!$this->roleModel->take(['id' => $id], ['id'])) {
            throw new LogicException('角色不存在');
        }

        if (isset($data['name'])) {
            $existingRole = $this->roleModel->take(['name' => $data['name']], ['id']);
            if ($existingRole && $existingRole['id'] != $id) {
                throw new LogicException('角色名称已存在');
            }
        }

        // 编辑关联权限
        if (isset($data['permissions']) && is_array($data['permissions'])) {
            // 查询现有权限
            $existingPermissions = $this->rolePermissionModel->search(['role_id' => $id], ['permission_id']);
            $existingPermissionIds = array_column($existingPermissions, 'permission_id');
            
            // 需要添加的权限
            $permissionsToAdd = array_diff($data['permissions'], $existingPermissionIds);
            foreach ($permissionsToAdd as $permissionId) {
                $this->rolePermissionModel->create([
                    'role_id' => $id,
                    'permission_id' => $permissionId
                ]);
            }
            
            // 需要删除的权限
            $permissionsToDelete = array_diff($existingPermissionIds, $data['permissions']);
            if (!empty($permissionsToDelete)) {
                $this->rolePermissionModel->where('role_id', $id)
                    ->whereIn('permission_id', $permissionsToDelete)
                    ->delete();
            }
        }

        $rows = $this->roleModel->modify($id, $data);
        return ['affected_rows' => $rows];
    }

    /**
     * 删除角色
     * @param int $id 角色ID
     * @return array
     * @throws LogicException
     */
    public function delete(int $id): array
    {
        if (!$this->roleModel->take(['id' => $id], ['id'])) {
            throw new LogicException('角色不存在');
        }

        $rows = $this->roleModel->remove($id);
        return ['affected_rows' => $rows];
    }

    /**
     * 获取所有角色
     * @return array
     */
    public function all(): array
    {
        $fields = ['id', 'name', 'description'];
        return $this->roleModel->search([], $fields);
    }
}
